package com.caiyi.financial.nirvana.sms.task;

import com.alibaba.fastjson.JSON;
import com.caiyi.financial.nirvana.sms.entity.SmsUser;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.queue.AlarmSendQueueEntity;
import com.caiyi.financial.nirvana.sms.util.CommUtil;
import com.caiyi.financial.nirvana.sms.util.HttpClientUtil;
import com.caiyi.financial.nirvana.sms.util.SignUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class AlarmMsgSendTask implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(AlarmMsgSendTask.class);
    private static final String ALARM_ACCOUNT = "alarm";
    private String alarmMsg;
    private String env;

    public AlarmMsgSendTask(String alarmMsg, String env) {
        this.alarmMsg = alarmMsg;
        this.env = env;
    }

    @Override
    public void run() {
        try {
            AlarmSendQueueEntity alarm = JSON.parseObject(alarmMsg, AlarmSendQueueEntity.class);
            String sendUrl = CommUtil.getSendUrl(env);
            Map params = new HashMap();
            params.put("account", ALARM_ACCOUNT);
            params.put("content", alarm.getContent());
            params.put("phones", alarm.getPhone());
            String userJson = JedisService.get(String.format(JedisKey.SMS_USER, ALARM_ACCOUNT));
            SmsUser apiUser = JSON.parseObject(userJson, SmsUser.class);
            String sign = SignUtil.createSign(params, apiUser.getPassword());
            params.put("sign", sign);
            String content = HttpClientUtil.doPost(sendUrl, JSON.toJSONString(params));
            logger.info("AlarmMsgSendTask request {} - {}, response {}", sendUrl, params, content);
        } catch (Exception e) {
            logger.error("AlarmMsgSendTask error!!!", e);
        }
    }
}
